package Leetcode.ArrayAndLinkedList.reverseList206;


/**
 * 反转一个单链表
 * 输入: 1->2->3->4->5->NULL
 * 输出: 5->4->3->2->1->NULL
 * <p>
 * 思路：遍历这个链表使得每一个节点指向其前一个节点
 * 改变当前节点指向前一个节点会导致当前节点的后继节点丢失，所以需要一个tmp保存剩下的链表
 */

/**
 * 次数2
 */
public class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null) {
            return head;
        }
        ListNode prev = null;
        ListNode cur = head;
        while (cur != null) {
           ListNode next = cur.next;
           cur.next = prev;
           prev = cur;
           cur = next;
        }
        return prev;
    }


    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4, 5};
        ListNode node = new ListNode(nums);
        System.out.println(node);
        Solution solution = new Solution();
        System.out.println(solution.reverseList(node));

    }
}
